package com.entities.projectversion.servlets;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.core.protocols.IKVObject;
import com.core.protocols.IServiceLayerDelegate;
import com.core.servlets.TaskTrackerServlet;
import com.core.utils.GlobalConstants;
import com.core.utils.ListUtils;
import com.core.utils.RequestParams;
import com.entities.projectversion.requestmapparser.ProjectVersionMapParser;
import com.entities.projectversion.servicelayer.VersionListLayer;
import com.model.project.Version;


public class VersionAdd
        extends TaskTrackerServlet
        implements IServiceLayerDelegate {

	private HttpServletResponse postResponse     = null;

	private Integer             parentProjectId  = null;

	private static final long   serialVersionUID = 1L;



	@Override
	protected void doGet ( HttpServletRequest request,
	                       HttpServletResponse response )
	        throws ServletException, IOException {

		this.parentProjectId = RequestParams.paramsFromRequest(request).integerAtIndexForKey(0, "projectId");

		super.doGet(request, response);
	}



	@SuppressWarnings("unchecked")
	@Override
	protected void doPost ( HttpServletRequest request,
	                        HttpServletResponse response )
	        throws ServletException, IOException {

		this.postResponse = response;


		Version template = null;
		Map <String, String[]> map = null;
		map = request.getParameterMap();
		template = ProjectVersionMapParser.fromMap(map);

		VersionListLayer versionListLayer = new VersionListLayer();
		versionListLayer.setLayerDelegate(this);
		versionListLayer.addProjectVersion(template, parentProjectId);


	}



	@Override
	public <T> void responseResponseItemsList ( final List <T> items,
	                                            final Object request,
	                                            final Exception exception ) {


		T item = ListUtils.listItemAtIndex(items, 0);

		this.redirectItemIntoOpenServlet(item);

	}



	private <T> void redirectItemIntoOpenServlet ( T item ) {

		if ( this.postResponse == null ) {
			return;
		}

		String redirection = String.format("%s", GlobalConstants.SERVLET_PROJECTLIST);

		if ( item != null ) {
			if ( item instanceof IKVObject ) {
				IKVObject kvObject = (IKVObject) item;
				String idValue = kvObject.idValue().toString();
				redirection = String.format("%s?%s", GlobalConstants.SERVLET_VERSIONINFO, idValue);
			}
		}

		try {
			this.postResponse.sendRedirect(redirection);
		} catch ( IOException e ) {
			e.printStackTrace();
		}

	}



}
